<?php

namespace app\admin\controller\facrm\contract;


use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Queue;


/**
 *合同管理
 */
class Index extends Backend
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'name,number';
    protected $childrenAdminIds = [];
    protected $noNeedRight = ['product', 'selectpage', 'payurl'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('\app\admin\model\facrm\Contract');
        $this->request->filter(['strip_tags']);
        \app\admin\model\AdminLog::setIgnoreRegex([
            '/^(.*)\/(selectBusiness|selectcontact)$/i',//不记录日志
        ]);
    }

    /**
     * 全部列表
     */
    public function index($scene_list = array())
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $scene_list = $scene_list ? $scene_list : ['all' => __('全部合同')];
        $customer_id = $this->request->param("customer_id");
        if ($this->request->isAjax()) {
            $filter_w = $this->getFilterWhere($scene_list);

            if ($customer_id) {
                $filter_w['customer_id'] = $customer_id;
            }
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            if (isset($filter['expire_handle'])) {
                if ($filter['expire_handle'] == 100) {//如果是查询需要回款的合同
                    $filter_w['money'] = ['exp', Db::raw('>return_money')];
                    unset($filter['expire_handle']);
                }

                $this->request->get(['filter' => json_encode($filter)]);
            }


            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $this->request->request(['custom' => $filter_w]);
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($filter_w)
                ->with([
                ])
                ->order($sort, $order)->fetchSql(false)
                ->count();
            $list = $this->model
                ->where($where)
                ->where($filter_w)
                ->with([
                    'createUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'orderAdmin' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'customer' => function ($customer) {
                        $customer->field('id,name');
                    },
                ])
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assignconfig('admin_id', $this->auth->id);

        /**
         * 自定义字段
         */
        $fields = \app\admin\model\facrm\Fields::getCustomFieldsTable('contract', [], 'isfilter=1 or islist=1');
        if ($fields) {
            $this->assignconfig('fields', json_encode($fields));
        }
        $this->view->assign("scene_list", $scene_list);

        $payConfig = \addons\facrm\library\Order::getPayConfig();
        $this->assignconfig('payConfig', ($payConfig ? $payConfig['values'] : []));



        $hiprint = get_addon_info('hiprint');
        if (!$hiprint || $hiprint['state']!=1) {
            $hiprint=false;
        }
        $this->assignconfig('hiprint', ($hiprint ? true : false));
        return $this->view->fetch('index');
    }


    /**
     * 我的下属/合同
     */
    public function lists()
    {
        $this->view->assign("action", 'lists');
        return $this->index(['owner' => '我的合同', 'branch' => '下属合同']);
    }

    /**
     * 我的下属/合同[添加]
     * @param null $customer_id
     */
    public function contractadd($customer_id = null)
    {

        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r = $flow->where('types', 'contract')->where("status", 1)->order('id desc')->find();
        if (!$flow_r) $this->error(__('审批配置不存在，请先配置'), url("facrm/flow/index"));
        $customer = model('\app\admin\model\facrm\Customer');
        $params = $this->request->post("row/a");

        $row_c = $customer->get(isset($params['customer_id']) ? $params['customer_id'] : $customer_id);

        if ($this->request->isPost()) {

            if (!isset($params['customer_id']))
                $this->error(__('请选择客户'));

            if (!$row_c)
                $this->error(__('没有找到客户'));

            //检查是否有权限
            $Auth = new  \addons\facrm\library\Auth();
            if (!$Auth->checkCustomerAuth($row_c, $this->auth)) {
                $this->error(__("您没有权限"));
            }
            $this->add();
        }

        $addon_config = get_addon_config('facrm');
        $this->view->assign("flow", $flow_r);
        $cprefix = $this->model::autoNo($addon_config['cprefix']);
        $this->view->assign("cprefix", $cprefix);//合同前缀
        $this->assignconfig("cprefix", $addon_config['cprefix']);
        return $this->view->fetch('add', ['addtype' => 'contractadd']);

    }


    /**
     * 详情
     * @param null $ids
     * @return string
     * @throws Exception
     */
    public function detail($ids = null)
    {

        $row = $this->model->with(['product'])->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row);

        return $this->view->fetch();

    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {

        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r =\app\admin\model\facrm\Flow::getFlow($this->auth->id, 'contract');

        if (!$flow_r) $this->error(__('审批配置不存在，请先配置'), url("facrm/flow/index"));

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!isset($params['customer_id']))
                $this->error(__('请选择客户'));

            $customer = model('\app\admin\model\facrm\Customer');
            $row_c = $customer->get($params['customer_id']);

            if (!$row_c)
                $this->error(__('没有找到客户'));

            $params['order_time'] = $params['order_time'] ? strtotime($params['order_time']) : 0;
            $params['start_time'] = $params['start_time'] ? strtotime($params['start_time']) : 0;
            $params['end_time'] = $params['end_time'] ? strtotime($params['end_time']) : 0;
            $params = array_merge($params, [
                'create_user_id' => $this->auth->id,
                'owner_user_id' => $this->auth->id,
                'type_id' => '1',
                'check_status' => 0,
                'source_id' => $row_c['source'] ? $row_c['source'] : 0,//来源ID客户可能会改，所以下单的时候要记录
            ]);

            $params = $this->preExcludeFields($params);

            $result = false;
            $contract_id = 0;
            Db::startTrans();
            try {
                $product_data = ($this->request->post("product/a"));
                $result = $this->model->add($params,$product_data);
                $contract_id = $this->model->id;
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                //处理合同审核流程
                $flow->addFlow($contract_id, $this->auth->id, 'contract', $flow_r);
                hook("facrm_contract_add", array_merge($params, ['id' => $contract_id]));
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }
        }

        $addon_config = get_addon_config('facrm');
        $this->view->assign("flow", $flow_r);
        $cprefix = $this->model::autoNo($addon_config['cprefix']);
        $this->view->assign("cprefix", $cprefix);//合同前缀
        $this->assignconfig("cprefix", $addon_config['cprefix']);
        return $this->view->fetch('add', ['addtype' => 'add']);
    }

    /**
     * 修改
     * @param null $ids
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $flow = model('\app\admin\model\facrm\Flow');
        if ($row->flow_id) {
            $flow->where('id', $row->flow_id);//处理流程被删除
        }
        $flow_r = $flow->where('types', 'contract')->where("status", 1)->find();

        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            if ($params) {
                if ($row->check_status == 2) {
                    //审核通过的只能修改负责人和备注、处理情况、续费单价
                    $params_update = array();
                    isset($params['remark']) ? $params_update['remark'] = $params['remark'] : '';
                    isset($params['owner_user_id']) ? $params_update['owner_user_id'] = $params['owner_user_id'] : '';
                    isset($params['expire_handle']) ? $params_update['expire_handle'] = $params['expire_handle'] : '';
                    isset($params['renewmoeny']) ? $params_update['renewmoeny'] = $params['renewmoeny'] : '';

                    $result = $row->allowField(true)->save($params_update);
                    return $this->success();
                }/* elseif ($row->check_status == 1) {
                    //审核中的不能修改
                    return $this->error(__("审核中的不能修改,请先驳回再修改"));
                }*/


                $params = $this->preExcludeFields($params);
                $params['order_time'] = $params['order_time'] ? strtotime($params['order_time']) : 0;
                $params['start_time'] = $params['start_time'] ? strtotime($params['start_time']) : 0;
                $params['end_time'] = $params['end_time'] ? strtotime($params['end_time']) : 0;
                $params['check_status'] = 0;//重新把合同改成待审核状态
                $result = false;
                $contract_id = $row->id;
                Db::startTrans();
                try {
                    $product_data = ($this->request->post("product/a"));
                    $result = $this->model->edit($row, $params, $product_data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //处理合同审核流程
                    $flow->addFlow($contract_id, $this->auth->id, 'contract', $flow_r);
                    hook("facrm_contract_edit", array_merge($params, ['id' => $contract_id]));
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("product_list", $row->product);
        $this->view->assign("flow", $flow_r);
        return $this->view->fetch();

    }

    /**
     * 合同变更
     * @param null $ids
     * @remark 暂时不做审批流程
     */
    public function change($ids = NULL){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row->check_status != 2){
            $this->error(__('不是审批通过的合同无需更变'));
        }
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            if ($params) {

                $params = $this->preExcludeFields($params);
                $params['order_time'] = $params['order_time'] ? strtotime($params['order_time']) : 0;
                $params['start_time'] = $params['start_time'] ? strtotime($params['start_time']) : 0;
                $params['end_time'] = $params['end_time'] ? strtotime($params['end_time']) : 0;
                $result = false;
                $contract_id = $row->id;
                Db::startTrans();
                try {
                    $product_data = ($this->request->post("product/a"));
                    $result = $this->model->edit($row, $params, $product_data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {

                    hook("facrm_contract_change", array_merge($params, ['id' => $contract_id]));
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("product_list", $row->product);
        return $this->view->fetch();
    }


    /**
     * 删除
     * @param string $ids
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->where('owner_user_id', 'in', $this->childrenAdminIds)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 合同产品
     * @Internal
     */
    public function product($business_id = null)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if (!$business_id) $this->error(__("商机ID有误"));

        $this->model = model("app\admin\model\\facrm\business\Product");

        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
            ->where($where)
            ->where('business_id', $business_id)
            ->order($sort, $order)
            ->count();

        $list = $this->model
            ->where($where)
            ->where('business_id', $business_id)
            ->with(['info'])
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();

        $list = collection($list)->toArray();
        $result = array("total" => $total, "rows" => $list);

        return json($result);


    }

    /**
     * 打印
     * @param null $ids
     */
    public function print($ids = null)
    {
        $row = $this->model->with(['product'])->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row);

        return $this->view->fetch();
    }


    /**
     * 选择商机
     */
    public function selectBusiness()
    {
        $this->model = model('\app\admin\model\facrm\Business');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {


            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {

                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->with([
                ])
                ->order($sort, $order)->fetchSql(false)
                ->count();
            $list = $this->model
                ->where($where)
                ->with([
                    'createUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'ownerUser' => function ($user) {
                        $user->field('id,username,nickname');
                    },
                    'customer' => function ($customer) {
                        $customer->field('id,name');
                    },
                ])
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        } else {

            $this->view->assign("scene_list");
        }
        return $this->view->fetch();
    }

    /**
     * 选择联系人
     * @return \think\response\Json
     */
    public function selectcontact()
    {
        $this->model = model('\app\admin\model\facrm\customer\Contacts');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
    }

    /**
     * 选择合同
     * @return \think\response\Json
     */
    public function selectpage()
    {
        $this->request->request(['showField' => 'name']);
        $this->request->request(['keyField' => 'id']);
        $this->request->request(['searchField' => array('name|id|number')]);
        return parent::selectpage(); // TODO: Change the autogenerated stub
    }

    /**
     * 处理过滤where条件
     * @return array
     */
    private function getFilterWhere($scene_list)
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];
        $filter['scene_id'] = isset($filter['scene_id']) ? $filter['scene_id'] : (array_keys($scene_list)[0]);
        if (isset($filter['scene_id'])) {

            if (!isset($scene_list[$filter['scene_id']])) {
                $this->error(__("您没有权限"));
            }
            switch ($filter['scene_id']) {
                case 'all':
                    //全部
                    break;
                case 'owner':
                    //我的
                    $filter_w['order_admin_id'] = $this->auth->id;
                    break;
                case 'branch':
                    //下级
                    $this->childrenAdminIds = $this->auth->getChildrenAdminIds(false);
                    $filter_w['order_admin_id'] = ['in', $this->childrenAdminIds];
                    break;
                default://其它的还做TODO
                    $filter_w['order_admin_id'] = $this->auth->id;
            }
            unset($filter['scene_id']);
            $this->request->get(['filter' => json_encode($filter)]);
        }
        return $filter_w;
    }

    /**
     * 生成续费链接
     * @param null $ids
     * @return string
     * @throws Exception
     */
    public function payurl($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $check_data = \addons\facrm\library\Order::checkPay($row, 'renew', $pay_config);
        if ($check_data['code'] != 1) {
            $this->error(__($check_data['msg']));
        }
        //10天就重新刷新支付凭证
        if (!$row->renewtoken || (time() - $row->update_time) > 864000) {
            $row->renewtoken = md5($row->id . uniqid() . Random::uuid());
            $row->save();
        }


        $url = addon_url('facrm/order/renew', ['pay_token' => $row->renewtoken], '', true);
        $this->view->assign("url", $url);
        $this->view->assign("row", $row);

        return $this->view->fetch();

    }


    /**
     * 销毁
     * @param null $ids
     */
    public function destroy($ids = null){
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $k => $v) {
                if ($v->check_status!=2){
                    //如果不是审核通过的就要还原库存
                    foreach ($v->product as $p){
                        $p->info()->setInc('inventory',$p['nums']);//恢复库存
                        $p->delete(true);
                    }
                }
                $count +=$v->delete(true);
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
